// ==UserScript==
// @name         Ti-0115-AutoCart
// @namespace    http://tampermonkey.net/
// @version      20220116
// @description  Ti-0115-AutoCart
// @author       Z
// @match        https://www.ti.com.cn/store/ti/*/cart*
// @match        https://www.ti.com/store/ti/*/cart*
// @icon         https://www.ti.com/favicon.ico
// @grant        GM_xmlhttpRequest
// @grant        GM_registerMenuCommand
// @grant        GM_getValue
// @grant        GM_setValue
// @require      https://www.ti.com.cn/store/_ui/responsive/common/js/jquery-2.1.1.min.js
// @require      http://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js


// ==/UserScript==

(function () {
  'use strict';
  ////debugger; UCC27211DDA
  //https://login.ti.com/idp/SSO.saml2

  const z_name = 'Ti';
  let P_WWW_0_COM = 'http://vip001.f3322.net:8081';
  //P_WWW_0_COM = 'http://192.168.1.250';

  let Z_SiJianJianGe = 500 + Math.floor(Math.random() * 3000); // 时间间隔

  let i_CaoSi = 18 * 1000;
  let url = window.location.href;
  let P_I_403 = 0;
  let P_I_K_403 = 0;
  let P_S_AkmUrl = '';
  let P_S_Abck_403 = '';
  let P_I_FHZ = -1;

  let P_I_A = 0;
  let P_I_CaoSi = 0;

  let P_B_CB_1 = false;
  let P_B_CB_2 = false;
  let P_B_CB_3 = false;
  let P_B_CB_4 = false;
  let P_B_CB_5 = false;
  let P_B_CB_6 = false;
  let P_B_CB_7 = false;
  let P_B_CB_8 = false;
  let P_B_CB_9 = false;

  let P_S_GP_1 = 'get';
  let P_S_GP_2 = 'post';
  let P_S_GP_3 = 'post';
  let P_S_GP_4 = 'get';
  let P_S_GP_5 = 'get';
  let P_S_GP_6 = 'post';
  let P_S_GP_7 = '';
  let P_S_GP_8 = '';
  let P_S_GP_9 = '';

  let P_S_Url_0 = 'https://www.ti.com.cn/store/ti/zh/checkout';

  let P_S_Url_1 = ''; // get
  let P_S_Url_2 = ''; // post
  let P_S_Url_3 = ''; //get
  let P_S_Url_4 = ''; // post
  let P_S_Url_5 = ''; // post
  let P_S_Url_6 = ''; // post
  let P_S_Url_7 = '';
  let P_S_Url_8 = '';
  let P_S_Url_9 = '';

  let P_S_Txt_1 = '';
  let P_S_Txt_2 = '';
  let P_S_Txt_3 = '';
  let P_S_Txt_4 = '';
  let P_S_Txt_5 = '';
  let P_S_Txt_6 = '';
  let P_S_Txt_7 = '';
  let P_S_Txt_8 = '';
  let P_S_Txt_9 = '';

  let P_I_BuZou = 0;

  let html;
  let b_html = false;
  let P_OPN_SL = '';

  let P_B_YiBu = false;
  let P_DangQianBuZou = -1;

  let P_URL_OLD = '';
  let P_B_JiSi = false;

  let P_B_Ajax_Send = false;

  // websocket参数 start
  let ipAddress = '';
  let websock = null; //建立的连接
  let  lockReconnect = false; //是否真正建立连接
  let  timeout = 20 * 1000; //20秒一次心跳
  let  timeoutObj = null; //心跳心跳倒计时
  let  serverTimeoutObj = null; //心跳倒计时
  let  timeoutNum = null; //断开 重连倒计时
  // websocket参数 end

  // 注入 html
  if (!b_html) {
    html =
      '\
<style>\
#z_all {\
  margin: 3px;\
  display: block;\
  width: 100%;\
  min-width:980px;\
}\
#z_all button:disabled {\
  background-color: #666;\
}\
.z_row {\
  display: block;\
  width: 100%;\
  height: 50px;\
  border: 1px solid rgb(85, 85, 85);\
  margin: 1px auto;\
  clear: both;\
}\
.z_row button {\
  display: block;\
  float: left;\
  width: 5%;\
  height: 38px;\
  margin: 6px 3px auto;\
}\
.z_row input {\
  display: block;\
  float: left;\
  width: 55%;\
  height: 38px;\
  margin: 6px 3px auto;\
}\
.z_row b{\
  display: block;\
  float: left;\
  margin: 15px 0 0 6px;\
}\
.z_row .cb {\
  display: block;\
  float: left;\
  width: 2%;\
  height: 38px;\
  margin: 6px 3px auto;\
}\
.z_row .time {\
  display: block;\
  float: left;\
  width: 3.6%;\
  height: 38px;\
  margin: 6px 3px auto;\
}\
#txtLog{\
  display: block;\
  float: left;\
  width: 91%;\
  height: 28px;\
  min-height: 28px;\
  margin: 3px 3px auto;\
}\
.z_row .gp,.z_row .url{\
width:3%;\
}\
.z_row .url{\
width:27%;\
}\
.z_opn,\
.z_sl {\
  float: left;\
  width: 120px;\
}\
.z_opn,\
.z_sl b {\
  display: block;\
  float: left;\
}\
.z_row .ok {\
}\
.z_row .wait {\
}\
</style>\
<hr />\
<div id="z_all">\
<div class="z_row" style="">\
<div class="z_opn" style="width:500px;color:red;"><b>盯货:</b><input id="txtDingHuo" value="" style="width:210px;"/>\
<b>最小数量:</b><input id="txtZXSL" value="500" style="width:80px;"/>\
</div>\
<div class="z_opn"><b>OPN:</b><input id="txtOpn" value="LM324N" /></div>\
  <div class="z_sl"><b>数量:</b><input id="txtSl" value="25" /></div>\
  <button id ="btnClear" style = "width:50px;" >清车</button>\
  <button id="btnAkm" style="width: 80px;">过403</button>\
  <button id = "btnSlHh" style = "width:80px;color:red;" >加+抢</button>\
  <div style="display:none">\
  <div class="z_opn" style="width:300px;display:none"><b>【数量】货号</b><input id="txtSlHh" value="" /></div>\
  <button id ="btnAdd" style = "width:50px;" >加车</button>\
  <button id ="btnQg" style="width:50px;">抢购</button>\
  <button id="btnAddQg" style="width:80px;display:none">加+抢</button>\
  <input id="txt0CaXun" />\
  <button id="btn0CaXun" style="width: 50px;">查询</button>\
  </div >\
  </div >\
  <div class="z_row" style="height: 90px;">\
    <textarea id="txtLog" style="width:99%;height: 80px;"></textarea>\
  </div>\
  <div class="z_row">\
    <button id="btn0">0</button>\
    <button id="btn0_gn">国内</button>\
    <button id="btn0_xjp">新加坡</button>\
    <button id="btn0_tg">泰国</button>\
    <button id="btn0_ReadAddr" style="width:80px;display:none">读取地址</button>\
    <button id="btn0_SaveAddr" style="width:80px">保存数据</button>\
    <button id="btn0_SaveAddr0" style="width:80px">初始地址</button>\
  </div>\
  <div class="z_row">\
    <button id="btn_2_1">1</button>\
    <input type="checkbox" id="cb1" class="cb" />\
    <input id="txt1gp" class="gp" value="get" />\
    <input id="txt1url" class="url" />\
    <input id="txt1" />\
    <input id="txt1time" class="time" />\
  </div>\
  <div class="z_row">\
    <button id="btn_2_2">2</button>\
    <input type="checkbox" id="cb2" class="cb" />\
    <input id="txt2gp" class="gp" value="get" />\
    <input id="txt2url" class="url" />\
    <input id="txt2" />\
    <input id="txt2time" class="time" />\
  </div>\
  <div class="z_row">\
    <button id="btn_2_3">3</button>\
    <input type="checkbox" id="cb3" class="cb" />\
    <input id="txt3gp" class="gp" value="get" />\
    <input id="txt3url" class="url" />\
    <input id="txt3" />\
    <input id="txt3time" class="time" />\
  </div>\
  <div class="z_row">\
    <button id="btn_2_4">4</button>\
    <input type="checkbox" id="cb4" class="cb" />\
    <input id="txt4gp" class="gp" value="get" />\
    <input id="txt4url" class="url" />\
    <input id="txt4" />\
    <input id="txt4time" class="time" />\
  </div>\
  <div class="z_row">\
    <button id="btn_2_5">5</button>\
    <input type="checkbox" id="cb5" class="cb" />\
    <input id="txt5gp" class="gp" value="get" />\
    <input id="txt5url" class="url" />\
    <input id="txt5" />\
    <input id="txt5time" class="time" />\
  </div>\
  <div class="z_row">\
    <button id="btn_2_6">6</button>\
    <input type="checkbox" id="cb6" class="cb" />\
    <input id="txt6gp" class="gp" value="get" />\
    <input id="txt6url" class="url" />\
    <input id="txt6" />\
    <input id="txt6time" class="time" />\
  </div>\
  <div class="z_row">\
    <button id="btn_2_7">7</button>\
    <input type="checkbox" id="cb7" class="cb" />\
    <input id="txt7gp" class="gp" value="get" />\
    <input id="txt7url" class="url" />\
    <input id="txt7" />\
    <input id="txt7time" class="time" />\
  </div>\
  <div class="z_row">\
    <button id="btn_2_8">8</button>\
    <input type="checkbox" id="cb8" class="cb" />\
    <input id="txt8gp" class="gp" value="get" />\
    <input id="txt8url" class="url" />\
    <input id="txt8" />\
    <input id="txt8time" class="time" />\
  </div>\
  <div class="z_row">\
    <button id="btn_2_9">9</button>\
    <input type="checkbox" id="cb9" class="cb" />\
    <input id="txt9gp" class="gp" value="get" />\
    <input id="txt9url" class="url" />\
    <input id="txt9" />\
    <input id="txt9time" class="time" />\
  </div>\
  <div class="z_row">\
    \
    <button id="btn1">1</button>\
    <button id="btn2">2</button>\
    <button id="btn3">3</button>\
    <button id="btn4">4</button>\
    <button id="btn5">5</button>\
    <button id="btn6">6</button>\
    <button id="btn7">7</button>\
    <button id="btn8">8</button>\
    <button id="btn9">9</button>\
  </div>\
  <div id="z_res"></div>\
</div >\
<hr />\
<button id="btnWebSocketLogin">websocket登录测试</button>\
  ';
  }

  setInterval(() => {
    if (b_html) return;

    if ($('.lower-header-area').length > 0) b_html = true;

    if (!b_html) return;

    $('.lower-header-area').html(html);

    z_f_btn0();
    z_f_Gn();

    P_S_AkmUrl = z_f_get_akm_url();
    // 处理 403
    let P_S_Abck_403 = '';

    // 定期 过 403
    // setInterval(() => {
    // 	z_do_403_1();
    // }, 1000 * 9);

    let P_D_JiSi = new Date();
    // 设置 Ajax 默认值。
    $.ajaxSetup({
      headers: {
        // Accept: "*/*",
        // "Accept-Language": "zh-CN",
        // "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        // "cache-control": "no-cache",
        // pragma: "no-cache",
        // "x-requested-with": "XMLHttpRequest",
      },
      cache: false,
      // async: false,
    });
    // 事件
    // Ajax
    $(document).ajaxStart(function () {
      //console.log("ajaxStart:[" + "" + "]");
    });

    $(document).ajaxSend(function (event, request, settings) {
      console.log(
        '------------------------------------------------------------------------'
      );

      console.log('ajaxSend:' + settings.url);
      P_B_Redis_3 = true;
      P_B_Ajax_Send = true;
      if (settings.url.indexOf('/buy?') > -1) {
        P_DangQianBuZou = 1;
        $('#txt1time').val('');
        $('#txt2time').val('');
        $('#txt3time').val('');
        $('#txt4time').val('');
        $('#txt5time').val('');
        $('#txt6time').val('');
        $('#txt7time').val('');
        $('#txt8time').val('');
        $('#txt9time').val('');
        //z_log('')
      }
      if (settings.url.indexOf('buy/multi/delivery-address/addSelected') > -1) {
        P_DangQianBuZou = 2;
      }
      if (settings.url.indexOf('/multi/cn-tax-invoice/add') > -1) {
        P_DangQianBuZou = 3;
      }
      if (settings.url.indexOf('/buy/multi/regulations-step/validate') > -1) {
        P_DangQianBuZou = 4;
      }
      if (settings.url.indexOf('/buy/multi/delivery-method/select') > -1) {
        P_DangQianBuZou = 5;
      }
      if (
        settings.url.indexOf(
          '/buy/multi/payment-method/citcon/addSelectedPayment'
        ) > -1
      ) {
        P_DangQianBuZou = 6;
      }

      if (P_DangQianBuZou >= 1) {
        P_B_JiSi = true;
        P_D_JiSi = new Date();
        $('#txt' + P_DangQianBuZou + 'time').val('0');
      }
      P_URL_OLD = settings.url;
    });
    $(document).ajaxSuccess(function (event, request, settings) {
      console.log('ajaxSuccess:[' + request.status + ']' + settings.url);
    });
    $(document).ajaxStop(function () {
      P_B_JiSi = false;
      //console.log("ajaxStop:[" + "" + "]");
    });
    $(document).ajaxError(function (event, request, settings) {
      ////console.log("ajaxError: [" + request.status + "] " + settings.url);
      let _url = settings.url;
      switch (request.status) {
        case 403:
          z_f_403(_url);
          break;
        case 428:
          z_f_428(_url);
          break;
        default:
          z_f_x_200(request.status, _url);
      }
      z_log('Err | ' + P_I_BuZou + ' | ' + request.status);
      P_B_JiSi = false;

      if (!P_B_CaKu) {
        P_B_CaKu = true; // 数据库停用
      }
    });
    $(document).ajaxComplete(function (event, request, settings) {
      console.log(request.responseText);
      if (typeof request.responseText == 'string') {
        if (request.responseText.indexOf('Add to cart checkout error') > -1) {
          z_log(' Err | 加车失败。');
        }
      }
      console.log('ajaxComplete:[' + request.status + ']' + settings.url);
      console.log(
        '------------------------------------------------------------------------'
      );
      P_B_Ajax_Send = false;
      //console.log(request);
      //console.log(settings);
      ////console.log(settings.url);
    });

    // 抢购步骤计时
    setInterval(() => {
      if (P_B_JiSi) {
        //if (P_B_JiSi) {
        let _e = new Date();
        let __t = (_e - P_D_JiSi) / 1000.0;
        $('#txt' + P_DangQianBuZou + 'time').val(__t.toFixed(2));
        // console.log('#txt' + P_DangQianBuZou + 'time');
        // console.log(_e);
        // console.log(P_D_JiSi);
      }
    }, 100);

    // 检测数据库抢购
    let P_B_CaKu = false;
    //let P_S_OLD_OPN = "";

    //
    let p_i = 0;
    let P_B_Redis_3 = false;

    setInterval(() => {
      if (P_B_Redis_3) return;
      if (P_B_Ajax_Send) return;

      P_B_Redis_3 = true;
      z_log('数据库：扫描');
      GM_xmlhttpRequest({
        url: P_WWW_0_COM + '/redis/3.php',
        method: 'get',
        onload: function (res) {
          //P_B_Redis_3 = false;
          if (res.status === 200 && typeof res.responseText != 'undefined') {
            let _a_res = res.responseText.split('|');
            if (_a_res.length == 2) {
              if (P_OPN_SL != res.responseText) {
                P_OPN_SL = res.responseText;
                let _txtDingHuo = $('#txtDingHuo').val();
                let _txtZXSL = $('#txtZXSL').val() * 1;

                z_log('数据库：发现 ' + res.responseText);
                let _do = false;

                if (_a_res[1] >= _txtZXSL) {
                  if (_txtDingHuo != '') {
                    if (_txtDingHuo == _a_res[0]) {
                      _do = true;
                    } else {
                      z_log('数据库：发现产品与盯货不符。');
                      //P_B_Redis_3 = false;
                    }
                  } else _do = true;
                  // 开始加+抢
                } else {
                  z_log(
                    '数据库：' + '发现产品库存数量 小于 ' + $('#txtZXSL').val()
                  );
                  //P_B_Redis_3 = false;
                }

                if (_do) {
                  $('#txtOpn').val(_a_res[0]);
                  $('#txtSl').val(_a_res[1]);
                  //z_f_SlHh();
                  z_f_Auto();
                }
              } else {
                //z_log('数据库：');
                //P_B_CaKu = false;
              }
            } else {
              P_B_Redis_3 = false;
            }
          } else {
            //z_log('数据库：' + res.responseText);
            P_B_Redis_3 = false;
          }
        },
        onerror: function (err) {
          console.log(err);
        },
      });
    }, 300);

    // 检测数据库
    setInterval(() => {
      return;
      if (!P_B_CaKu) {
        z_log('数据库：开始');
        console.log(1);
        P_B_CaKu = true;

        if (typeof $('#txtDingHuo').val() != 'undefined') {
          GM_xmlhttpRequest({
            url: P_WWW_0_COM + '/redis/3.php',
            method: 'get',
            onload: function (res) {
              if (
                res.status === 200 &&
                typeof res.responseText != 'undefined'
              ) {
                console.log(res.responseText);
                let _a_res = res.responseText.split('|');
                if (_a_res.length == 2) {
                  if (P_OPN_SL != res.responseText) {
                    P_OPN_SL = res.responseText;
                    z_log('数据库:' + res.responseText);
                    if (_a_res[1] > 0) {
                      $('#txtOpn').val(_a_res[0]);
                      $('#txtSl').val(_a_res[1]);

                      let _txtDingHuo = $('#txtDingHuo').val();
                      let _txtZXSL = $('#txtZXSL').val() * 1;
                      let _do = false;
                      if (_txtDingHuo != '') {
                        if (_txtDingHuo == _a_res[0] && _a_res[1] >= _txtZXSL)
                          _do = true;
                      } else {
                        if (_a_res[1] >= _txtZXSL) _do = true;
                      }
                      // 开始加+抢
                      if (_do) {
                        z_f_SlHh();
                      }
                    } else {
                      P_B_CaKu = false;
                    }
                  } else {
                    z_log('数据库：符合条件记录');
                    P_B_CaKu = false;
                  }
                } else {
                  P_B_CaKu = false;
                }
              } else {
                P_B_CaKu = false;
              }
            },
            onerror: function (err) {
              console.log(err);
            },
          });
        } else {
          P_B_CaKu = false;
          console.log('--Wait AKM--');
        }
      }
    }, 1000 * 0.5);

    $('#z_all').on('click', '#btn0CaXun', function () {
      //z_f_ReadAddr();***
    });

    // 初始地址
    $('#z_all').on('click', '#btn0_SaveAddr0', function () {
      //z_f_ReadAddr();***

      P_B_CB_1 = true;
      P_B_CB_2 = true;
      P_B_CB_3 = true;
      P_B_CB_4 = true;
      P_B_CB_5 = true;
      P_B_CB_6 = true;
      P_B_CB_7 = false;
      P_B_CB_8 = false;
      P_B_CB_9 = false;

      P_S_GP_1 = 'get';
      P_S_GP_2 = 'post';
      P_S_GP_3 = 'post';
      P_S_GP_4 = 'get';
      P_S_GP_5 = 'get';
      P_S_GP_6 = 'post';
      P_S_GP_7 = '';
      P_S_GP_8 = '';
      P_S_GP_9 = '';
      P_S_Url_0 = 'https://www.ti.com.cn/store/ti/zh/checkout';
      P_S_Url_1 = '/buy';
      P_S_Url_2 = '/buy/multi/delivery-address/addSelected';
      P_S_Url_3 = '/multi/cn-tax-invoice/add'; //get
      P_S_Url_4 =
        '/buy/multi/regulations-step/validate?militaryFlag=No&eeId=14230&eeName=Laser+TV&appId=11830&appName=TV&selectedIOR=&_=1642688651140'; // post
      P_S_Url_5 =
        '/buy/multi/delivery-method/select?delivery_method=v2-china-DOM-1k_10k-EH&termsAccepted=Yes'; // post
      P_S_Url_6 = '/buy/multi/payment-method/citcon/addSelectedPayment'; // post
      P_S_Url_7 = '';
      P_S_Url_8 = '';
      P_S_Url_9 = '';
      P_S_Txt_1 = '';
      P_S_Txt_2 =
        'addressType=Business&countryIso=CN&editAddress=true&addressId=9140031258647&shippingAddress=true&firstName=Xiao&lastName=Bai&line1=FuTianQu+ZhenZhong+Road&line2=GuoLi+building+2211&townCity=ShenZhen&state=GuangDong&gstn=&panNumber=&sezCustomer=&postcode=518000&companyName=JunYuanSheng+Inc.+Co&companyUrl=www.co&phoneCountryPrefix=86-CN&phoneNumber=860+7558+4871187&phoneExtension=&email=xbti001%40outlook.com&middleName2=myTI+profile+address&taxExemptValidated=false&same_billingAddress=on&billingAddress=true&CSRFToken=11111111-1111-1111-1111-111111111111';
      P_S_Txt_3 =
        'id=8859736581768&type=EINVOICE&recipientType=COMPANY&recipient=深圳市也腾达电子有限公司&vatInvoiceTitleFlag=true&taxRegistrationNumber=91440300MA5G5HP54F&registrationAddress=深圳市福田区华强北街道华航社区中航路42号中航北苑大厦10-B2&phoneNumber=132+6559+4979&bankName=开户银行++中国工商银行股份有限公司深圳振华支行+&bankAccountNo=4000+0217+0920+0576+611&vatInvoiceAddress.firstName=&vatInvoiceAddress.companyName=&vatInvoiceAddress.phoneCountryPrefix=0&vatInvoiceAddress.phoneNumber=&billTo_countryIso=0&vatInvoiceAddress.countryIso=CN&vatInvoiceAddress.line1=&vatInvoiceAddress.townCity=&vatInvoiceAddress.state=&vatInvoiceAddress.postcode=&phone1=0&mobileNumber=132+6559+4979&email=gwcb07%40e58.org&CSRFToken=11111111-1111-1111-1111-111111111111';
      P_S_Txt_4 = '';
      P_S_Txt_5 = '';
      P_S_Txt_6 =
        'paymentMethod=unionpay&CSRFToken=11111111-1111-1111-1111-111111111111';
      P_S_Txt_7 = '';
      P_S_Txt_8 = '';
      P_S_Txt_9 = '';

      GM_setValue('P_B_CB_1', P_B_CB_1);
      GM_setValue('P_B_CB_2', P_B_CB_2);
      GM_setValue('P_B_CB_3', P_B_CB_3);
      GM_setValue('P_B_CB_4', P_B_CB_4);
      GM_setValue('P_B_CB_5', P_B_CB_5);
      GM_setValue('P_B_CB_6', P_B_CB_6);
      GM_setValue('P_B_CB_7', P_B_CB_7);
      GM_setValue('P_B_CB_8', P_B_CB_8);
      GM_setValue('P_B_CB_9', P_B_CB_9);

      GM_setValue('P_S_GP_1', P_S_GP_1);
      GM_setValue('P_S_GP_2', P_S_GP_2);
      GM_setValue('P_S_GP_3', P_S_GP_3);
      GM_setValue('P_S_GP_4', P_S_GP_4);
      GM_setValue('P_S_GP_5', P_S_GP_5);
      GM_setValue('P_S_GP_6', P_S_GP_6);
      GM_setValue('P_S_GP_7', P_S_GP_7);
      GM_setValue('P_S_GP_8', P_S_GP_8);
      GM_setValue('P_S_GP_9', P_S_GP_9);

      GM_setValue('P_S_Txt_1', P_S_Txt_1);
      GM_setValue('P_S_Txt_2', P_S_Txt_2);
      GM_setValue('P_S_Txt_3', P_S_Txt_3);
      GM_setValue('P_S_Txt_4', P_S_Txt_4);
      GM_setValue('P_S_Txt_5', P_S_Txt_5);
      GM_setValue('P_S_Txt_6', P_S_Txt_6);
      GM_setValue('P_S_Txt_7', P_S_Txt_7);
      GM_setValue('P_S_Txt_8', P_S_Txt_8);
      GM_setValue('P_S_Txt_9', P_S_Txt_9);

      GM_setValue('P_S_Url_1', P_S_Url_1);
      GM_setValue('P_S_Url_2', P_S_Url_2);
      GM_setValue('P_S_Url_3', P_S_Url_3);
      GM_setValue('P_S_Url_4', P_S_Url_4);
      GM_setValue('P_S_Url_5', P_S_Url_5);
      GM_setValue('P_S_Url_6', P_S_Url_6);
      GM_setValue('P_S_Url_7', P_S_Url_7);
      GM_setValue('P_S_Url_8', P_S_Url_8);
      GM_setValue('P_S_Url_9', P_S_Url_9);

      z_f_Gn();
    });

    // 读取地址
    $('#z_all').on('click', '#btn0_ReadAddr', function () {
      z_f_ReadAddr();
    });

    // 保存数据
    $('#z_all').on('click', '#btn0_SaveAddr', function () {
      P_B_CB_1 = $('#cb1').prop('checked');
      P_B_CB_2 = $('#cb2').prop('checked');
      P_B_CB_3 = $('#cb3').prop('checked');
      P_B_CB_4 = $('#cb4').prop('checked');
      P_B_CB_5 = $('#cb5').prop('checked');
      P_B_CB_6 = $('#cb6').prop('checked');
      P_B_CB_7 = $('#cb7').prop('checked');
      P_B_CB_8 = $('#cb8').prop('checked');
      P_B_CB_9 = $('#cb9').prop('checked');

      P_S_GP_1 = $('#txt1gp').val();
      P_S_GP_2 = $('#txt2gp').val();
      P_S_GP_3 = $('#txt3gp').val();
      P_S_GP_4 = $('#txt4gp').val();
      P_S_GP_5 = $('#txt5gp').val();
      P_S_GP_6 = $('#txt6gp').val();
      P_S_GP_7 = $('#txt7gp').val();
      P_S_GP_8 = $('#txt8gp').val();
      P_S_GP_9 = $('#txt9gp').val();

      P_S_Url_1 = $('#txt1url').val();
      P_S_Url_2 = $('#txt2url').val();
      P_S_Url_3 = $('#txt3url').val();
      P_S_Url_4 = $('#txt4url').val();
      P_S_Url_5 = $('#txt5url').val();
      P_S_Url_6 = $('#txt6url').val();
      P_S_Url_7 = $('#txt7url').val();
      P_S_Url_8 = $('#txt8url').val();
      P_S_Url_9 = $('#txt9url').val();

      P_S_Txt_1 = $('#txt1').val();
      P_S_Txt_2 = $('#txt2').val();
      P_S_Txt_3 = $('#txt3').val();
      P_S_Txt_4 = $('#txt4').val();
      P_S_Txt_5 = $('#txt5').val();
      P_S_Txt_6 = $('#txt6').val();
      P_S_Txt_7 = $('#txt7').val();
      P_S_Txt_8 = $('#txt8').val();
      P_S_Txt_9 = $('#txt9').val();

      GM_setValue('P_B_CB_1', P_B_CB_1);
      GM_setValue('P_B_CB_2', P_B_CB_2);
      GM_setValue('P_B_CB_3', P_B_CB_3);
      GM_setValue('P_B_CB_4', P_B_CB_4);
      GM_setValue('P_B_CB_5', P_B_CB_5);
      GM_setValue('P_B_CB_6', P_B_CB_6);
      GM_setValue('P_B_CB_7', P_B_CB_7);
      GM_setValue('P_B_CB_8', P_B_CB_8);
      GM_setValue('P_B_CB_9', P_B_CB_9);

      GM_setValue('P_S_GP_1', P_S_GP_1);
      GM_setValue('P_S_GP_2', P_S_GP_2);
      GM_setValue('P_S_GP_3', P_S_GP_3);
      GM_setValue('P_S_GP_4', P_S_GP_4);
      GM_setValue('P_S_GP_5', P_S_GP_5);
      GM_setValue('P_S_GP_6', P_S_GP_6);
      GM_setValue('P_S_GP_7', P_S_GP_7);
      GM_setValue('P_S_GP_8', P_S_GP_8);
      GM_setValue('P_S_GP_9', P_S_GP_9);

      GM_setValue('P_S_Txt_1', P_S_Txt_1);
      GM_setValue('P_S_Txt_2', P_S_Txt_2);
      GM_setValue('P_S_Txt_3', P_S_Txt_3);
      GM_setValue('P_S_Txt_4', P_S_Txt_4);
      GM_setValue('P_S_Txt_5', P_S_Txt_5);
      GM_setValue('P_S_Txt_6', P_S_Txt_6);
      GM_setValue('P_S_Txt_7', P_S_Txt_7);
      GM_setValue('P_S_Txt_8', P_S_Txt_8);
      GM_setValue('P_S_Txt_9', P_S_Txt_9);

      GM_setValue('P_S_Url_1', P_S_Url_1);
      GM_setValue('P_S_Url_2', P_S_Url_2);
      GM_setValue('P_S_Url_3', P_S_Url_3);
      GM_setValue('P_S_Url_4', P_S_Url_4);
      GM_setValue('P_S_Url_5', P_S_Url_5);
      GM_setValue('P_S_Url_6', P_S_Url_6);
      GM_setValue('P_S_Url_7', P_S_Url_7);
      GM_setValue('P_S_Url_8', P_S_Url_8);
      GM_setValue('P_S_Url_9', P_S_Url_9);

      GM_setValue('P_S_DingHuo', $('#txtDingHuo').val());
    });

    $('#z_all').on('click', '#btnSlHh', function () {
      //z_f_getOpnSL();
      P_OPN_SL = $('#txtOpn').val() + '|' + $('#txtSl').val();
      z_f_SlHh();
    });
    // 点击 国内配置
    $('#z_all').on('click', '#btn0_gn', function () {
      z_f_Gn();
    });

    $('#z_all').on('click', '#btn0', function () {
      a1();
    });

    // 添加购物车
    function z_f_addCart(opn, sl) {
      // 清空 计时器。
      $('#txt1time').val('');
      $('#txt2time').val('');
      $('#txt3time').val('');
      $('#txt4time').val('');
      $('#txt5time').val('');
      $('#txt6time').val('');
      $('#txt7time').val('');
      $('#txt8time').val('');
      $('#txt9time').val('');
      //
      if (sl <= 0) return;

      let _url = '/occservices/v2/ti/addtocart';
      let _data =
        '{"cartRequestList":[{"opnId":"AAAAAAAAA","quantity":99999,"packageOption":null,"tiAddtoCartSource":"ti.com-quickcart"}],"currency":"CNY"}';
      //_data = "{\"cartRequestList\":[{\"packageOption\":\"CTX\",\"opnId\":\"AAAAAAAAA\",\"quantity\":\"99999\",\"tiAddtoCartSource\":\"store-pdp\",\"sparam\":\"\"}],\"currency\":\"CNY\"}";
      _data = _data.replace('AAAAAAAAA', opn);
      _data = _data.replace('99999', sl);

      //console.log("开始：Add");
      z_log('开始加购');
      $.ajax({
        type: 'post',
        url: _url,
        data: _data,
        timeout: P_I_CaoSi,
        headers: {
          'Content-Type': 'application/json;charset=utf8',
          'cache-control': 'no-cache',
          pragma: 'no-cache',
          'x-requested-with': 'XMLHttpRequest',
        },
        //contentType: "application/x-www-form-urlencoded",
        Accept: '*/*',
        cache: false,
        //async:false,
      }).done(function (d) {
        //console.log(d);
        if (d) {
          if (d.cartId) {
            //console.log(d.message);
            if (d.message.indexOf('Items added to the cart') > -1) {
              console.log('加车完毕。');
              // ---------------
              let _url = '/occservices/v2/ti/orderables/inventory';
              $.get(_url, null, function (res) {
                $.each(res, function (index, value) {
                  //-----------------
                  $('#txtSl').val(value.quantity);

                  ////////////////////////////////////
                  //if (value.quantity > 10000) $("#txtSl").val("1111");
                  ////////////////////////////////////

                  let _old_CSRFToken = '11111111-1111-1111-1111-111111111111';
                  let _new_CSRFToken = ACC.config.CSRFToken;
                  //let __gp = $("#txt" + P_I_BuZou + "gp").val();
                  let __url = '/store/ti/zh/cart/update';
                  let __data =
                    'entryNumber=0&productCode=LM324N&initialQuantity=' +
                    sl +
                    '&carrierOption=CutTape&quantity=500&CSRFToken=11111111-1111-1111-1111-111111111111';
                  __data = __data.replace(_old_CSRFToken, _new_CSRFToken);
                  __data = __data.replace('LM324N', value.orderableMaterial);
                  __data = __data.replace('500', $('#txtSl').val());
                  __data = __data.replace(_old_CSRFToken, _new_CSRFToken);
                  console.log('数量修改完毕。');
                  $.post(__url, __data, function (d) {
                    P_I_FHZ = -1;
                    z_f_Gn();
                    P_I_FHZ = 100;
                    a1();
                  });
                  //-----------------
                });
              });
              // ----------------
              //z_log("加车完毕。");
            } else {
              z_log(d.message);
            }
          } else {
            z_log(d.message);
          }
        }
      });
    }
    //加
    $('#z_all').on('click', '#btnAdd', function () {
      z_f_addCart($('#txtOpn').val(), $('#txtSl').val(), $('#txtSl').val());
    });

    //抢
    $('#z_all').on('click', '#btnQg', function () {
      P_I_FHZ = -1;
      z_f_Gn();
      //console.log("-----  自动抢购:开始  -----111");
      P_I_FHZ = 100;
      a1();
    });

    //加+抢
    let P_B_AddQg = false;
    function z_f_AddQg() {
      if (P_B_AddQg) {
        return;
      }
      P_B_AddQg = true;

      let _url = '/occservices/v2/ti/addtocart';
      let _data =
        '{"cartRequestList":[{"opnId":"AAAAAAAAA","quantity":99999,"packageOption":null,"tiAddtoCartSource":"ti.com-quickcart"}],"currency":"CNY"}';
      //_data = "{\"cartRequestList\":[{\"packageOption\":\"CTX\",\"opnId\":\"AAAAAAAAA\",\"quantity\":\"99999\",\"tiAddtoCartSource\":\"store-pdp\",\"sparam\":\"\"}],\"currency\":\"CNY\"}";
      _data = _data.replace('AAAAAAAAA', $('#txtOpn').val());
      _data = _data.replace('99999', $('#txtSl').val());
      z_log('加购：开始加车');
      $.ajax({
        type: 'post',
        url: _url,
        data: _data,
        timeout: P_I_CaoSi,
        headers: {
          'Content-Type': 'application/json;charset=utf8',
          'cache-control': 'no-cache',
          pragma: 'no-cache',
          'x-requested-with': 'XMLHttpRequest',
        },
        //contentType: "application/x-www-form-urlencoded",
        Accept: '*/*',
        cache: false,
        //async:false,
      })
        .done(function (d) {
          //console.log(d);
          if (d) {
            if (d.cartId) {
              //console.log(d.message);
              if (d.message.indexOf('Items added to the cart') > -1) {
                //console.log("加车完毕。");
                z_log('加购：完成加车');
                a1();
                //}, 1);
              }
            }
          }
        })
        .fail(function (f) {
          //console.log(f);
          switch (f.status) {
            case 403:
              z_f_403(_url);
              break;
            case 428:
              z_f_428(_url);
              break;
            default:
              z_f_x_200(f.status, _url);
          }
        });
    }
    $('#z_all').on('click', '#btnAddQg', function () {
      z_f_AddQg();
    });

    $('#z_all').on('click', '#btnAkm', function () {
      z_f_get_akm_url();
      z_do_403('');
    });

    $('#z_all').on('click', '#btn_2_1', function () {
      //debugger;
      let _gp = $('#txt' + $(this).text() + 'gp').val();
      let _url = P_S_Url_0 + $('#txt' + $(this).text() + 'url').val();
      let _body = $('#txt' + $(this).text()).val();
      P_B_YiBu = true;
      a(_gp, _url, _body);
      //g1(_url);
    });
    $('#z_all').on('click', '#btn_2_2', function () {
      let _gp = $('#txt' + $(this).text() + 'gp').val();
      let _url = P_S_Url_0 + $('#txt' + $(this).text() + 'url').val();
      let _body = $('#txt' + $(this).text()).val();
      a(_gp, _url, _body);
    });
    $('#z_all').on('click', '#btn_2_3', function () {
      P_B_YiBu = false;
      let _gp = $('#txt' + $(this).text() + 'gp').val();
      let _url = P_S_Url_0 + $('#txt' + $(this).text() + 'url').val();
      let _body = $('#txt' + $(this).text()).val();
      a(_gp, _url, _body);
    });
    $('#z_all').on('click', '#btn_2_4', function () {
      let _gp = $('#txt' + $(this).text() + 'gp').val();
      let _url = P_S_Url_0 + $('#txt' + $(this).text() + 'url').val();
      let _body = $('#txt' + $(this).text()).val();
      a(_gp, _url, _body);
    });
    $('#z_all').on('click', '#btn_2_5', function () {
      let _gp = $('#txt' + $(this).text() + 'gp').val();
      let _url = P_S_Url_0 + $('#txt' + $(this).text() + 'url').val();
      let _body = $('#txt' + $(this).text()).val();
      a(_gp, _url, _body);
    });
    $('#z_all').on('click', '#btn_2_6', function () {
      let _gp = $('#txt' + $(this).text() + 'gp').val();
      let _url = P_S_Url_0 + $('#txt' + $(this).text() + 'url').val();
      let _body = $('#txt' + $(this).text()).val();
      a(_gp, _url, _body);
    });
    $('#z_all').on('click', '#btn_2_7', function () {
      let _gp = $('#txt' + $(this).text() + 'gp').val();
      let _url = P_S_Url_0 + $('#txt' + $(this).text() + 'url').val();
      let _body = $('#txt' + $(this).text()).val();
      a(_gp, _url, _body);
    });
    $('#z_all').on('click', '#btn_2_8', function () {
      let _gp = $('#txt' + $(this).text() + 'gp').val();
      let _url = P_S_Url_0 + $('#txt' + $(this).text() + 'url').val();
      let _body = $('#txt' + $(this).text()).val();
      a(_gp, _url, _body);
    });
    $('#z_all').on('click', '#btn_2_9', function () {
      let _gp = $('#txt' + $(this).text() + 'gp').val();
      let _url = P_S_Url_0 + $('#txt' + $(this).text() + 'url').val();
      let _body = $('#txt' + $(this).text()).val();
      a(_gp, _url, _body);
    });
    $('#z_all').on('click', '#btnClear', function () {
      let _gp = 'post';
      let _url = '/store/ti/zh/myaccount/saved-cart/clear';
      let _body = 'CSRFToken=11111111-1111-1111-1111-111111111111';
      a(_gp, _url, _body);
    });

    // 函数

    // 国内
    function z_f_Gn() {
      z_f_btn0();
      P_S_Url_0 = '/store/ti/zh/checkout';
      z_f_ReadAddr();
      //$('#cb9').prop("checked") 获取
      //$('#cb9').attr("checked", false); 设置  //jquery 1.8.3 后，第二次失效。
      $('#cb1').prop('checked', P_B_CB_1);
      $('#cb2').prop('checked', P_B_CB_2);
      $('#cb3').prop('checked', P_B_CB_3);
      $('#cb4').prop('checked', P_B_CB_4);
      $('#cb5').prop('checked', P_B_CB_5);
      $('#cb6').prop('checked', P_B_CB_6);
      $('#cb7').prop('checked', P_B_CB_7);
      $('#cb8').prop('checked', P_B_CB_8);
      $('#cb9').prop('checked', P_B_CB_9);

      $('#txt1gp').val(P_S_GP_1);
      $('#txt2gp').val(P_S_GP_2);
      $('#txt3gp').val(P_S_GP_3);
      $('#txt4gp').val(P_S_GP_4);
      $('#txt5gp').val(P_S_GP_5);
      $('#txt6gp').val(P_S_GP_6);
      $('#txt7gp').val(P_S_GP_7);
      $('#txt8gp').val(P_S_GP_8);
      $('#txt9gp').val(P_S_GP_9);

      $('#txt1url').val(P_S_Url_1);
      $('#txt2url').val(P_S_Url_2);
      $('#txt3url').val(P_S_Url_3);
      $('#txt4url').val(P_S_Url_4);
      $('#txt5url').val(P_S_Url_5);
      $('#txt6url').val(P_S_Url_6);
      $('#txt7url').val(P_S_Url_7);
      $('#txt8url').val(P_S_Url_8);
      $('#txt9url').val(P_S_Url_9);

      $('#txt1').val(P_S_Txt_1);
      $('#txt2').val(P_S_Txt_2);
      $('#txt3').val(P_S_Txt_3);
      $('#txt4').val(P_S_Txt_4);
      $('#txt5').val(P_S_Txt_5);
      $('#txt6').val(P_S_Txt_6);
      $('#txt7').val(P_S_Txt_7);
      $('#txt8').val(P_S_Txt_8);
      $('#txt9').val(P_S_Txt_9);

      $('#txtDingHuo').val(GM_getValue('P_S_DingHuo'));
    }
    // 点击 查询
    //

    function z_f_ReadAddr() {
      if (typeof GM_getValue('P_S_GP_1') == 'string') {
        P_B_CB_1 = GM_getValue('P_B_CB_1');
        P_B_CB_2 = GM_getValue('P_B_CB_2');
        P_B_CB_3 = GM_getValue('P_B_CB_3');
        P_B_CB_4 = GM_getValue('P_B_CB_4');
        P_B_CB_5 = GM_getValue('P_B_CB_5');
        P_B_CB_6 = GM_getValue('P_B_CB_6');
        P_B_CB_7 = GM_getValue('P_B_CB_7');
        P_B_CB_8 = GM_getValue('P_B_CB_8');
        P_B_CB_9 = GM_getValue('P_B_CB_9');

        P_S_GP_1 = GM_getValue('P_S_GP_1');
        P_S_GP_2 = GM_getValue('P_S_GP_2');
        P_S_GP_3 = GM_getValue('P_S_GP_3');
        P_S_GP_4 = GM_getValue('P_S_GP_4');
        P_S_GP_5 = GM_getValue('P_S_GP_5');
        P_S_GP_6 = GM_getValue('P_S_GP_6');
        P_S_GP_7 = GM_getValue('P_S_GP_7');
        P_S_GP_8 = GM_getValue('P_S_GP_8');
        P_S_GP_9 = GM_getValue('P_S_GP_9');

        P_S_Txt_1 = GM_getValue('P_S_Txt_1');
        P_S_Txt_2 = GM_getValue('P_S_Txt_2');
        P_S_Txt_3 = GM_getValue('P_S_Txt_3');
        P_S_Txt_4 = GM_getValue('P_S_Txt_4');
        P_S_Txt_5 = GM_getValue('P_S_Txt_5');
        P_S_Txt_6 = GM_getValue('P_S_Txt_6');
        P_S_Txt_7 = GM_getValue('P_S_Txt_7');
        P_S_Txt_8 = GM_getValue('P_S_Txt_8');
        P_S_Txt_9 = GM_getValue('P_S_Txt_9');

        P_S_Url_1 = GM_getValue('P_S_Url_1');
        P_S_Url_2 = GM_getValue('P_S_Url_2');
        P_S_Url_3 = GM_getValue('P_S_Url_3');
        P_S_Url_4 = GM_getValue('P_S_Url_4');
        P_S_Url_5 = GM_getValue('P_S_Url_5');
        P_S_Url_6 = GM_getValue('P_S_Url_6');
        P_S_Url_7 = GM_getValue('P_S_Url_7');
        P_S_Url_8 = GM_getValue('P_S_Url_8');
        P_S_Url_9 = GM_getValue('P_S_Url_9');

        z_f_set_Url_5($('#txtSl').val()); //
      }
    }

    // 查询

    function z_f_set_Url_5(i_SuLiang) {
      if (i_SuLiang <= 1000) {
        P_S_Url_5 =
          '/buy/multi/delivery-method/select?delivery_method=v2-china-DOM-0_1k-EH&termsAccepted=Yes'; // post
      } else if (i_SuLiang <= 10000) {
        P_S_Url_5 =
          '/buy/multi/delivery-method/select?delivery_method=v2-china-DOM-1k_10k-EH&termsAccepted=Yes'; // post
      } else if (i_SuLiang <= 25000) {
        P_S_Url_5 =
          '/buy/multi/delivery-method/select?delivery_method=v2-china-DOM-10k_25k-EH&termsAccepted=Yes'; // post
      } else if (i_SuLiang <= 50000) {
        P_S_Url_5 =
          '/buy/multi/delivery-method/select?delivery_method=v2-china-DOM-25k_50k-EH&termsAccepted=Yes'; // post
      } else if (i_SuLiang <= 100000) {
        P_S_Url_5 =
          '/buy/multi/delivery-method/select?delivery_method=v2-china-DOM-50k_100k-EH&termsAccepted=Yes'; // post
      } else {
        P_S_Url_5 =
          '/buy/multi/delivery-method/select?delivery_method=v2-china-DOM-100k_1M-EH&termsAccepted=Yes'; // post
      }
      GM_setValue('P_S_Url_5', P_S_Url_5);
    }

    // 自动付款
    function z_f_Auto() {
      // let _a = P_OPN_SL.split('|');
      // if (_a.length == 2) {
      // 	z_f_set_Url_5(_a[1]);
      // 	P_I_FHZ = -1;
      // 	z_f_Gn();

      // 	console.log('-----  自动付款:开始  -----');
      // 	P_I_FHZ = 100;
      // 	z_f_btn0();
      // 	P_I_BuZou = 0;
      // 	z_f_a();
      // } else {
      // 	z_log('自动付款:[结束]' + P_OPN_SL);
      // 	P_B_Redis_3 = false; //
      // }
      z_f_SlHh();
    }

    // 数量 货号
    function z_f_SlHh() {
      P_OPN_SL = $('#txtOpn').val() + '|' + $('#txtSl').val();
      z_do_403(); // 过  403
      let _a = P_OPN_SL.split('|');
      if (_a.length == 2) {
        z_f_set_Url_5(_a[1]);
        P_I_FHZ = -1;
        z_f_Gn();
        console.log('-----  自动抢购:开始  -----');
        P_I_FHZ = 100;
        P_B_AddQg = false;
        z_f_AddQg();
      } else {
        z_log('加抢:[结束]' + P_OPN_SL);
        P_B_Redis_3 = false; //
      }
    }

    // 获取 Cookie
    function z_GetCookie(name) {
      var nameEQ = name + '=';
      var ca = document.cookie.split(';');
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
      }
      return null;
    }

    // 同步回调
    function z_f_a() {
      P_I_BuZou++;
      if (P_I_BuZou >= 10) {
        P_I_BuZou = 0;
        return;
      }
      let _old_CSRFToken = '11111111-1111-1111-1111-111111111111';
      let _new_CSRFToken = ACC.config.CSRFToken;
      let __cb = $('#cb' + P_I_BuZou).prop('checked');
      let __gp = $('#txt' + P_I_BuZou + 'gp').val();
      let __url = P_S_Url_0 + $('#txt' + P_I_BuZou + 'url').val();
      let __data = $('#txt' + P_I_BuZou).val();
      __data = __data.replace(_old_CSRFToken, _new_CSRFToken);
      if (__cb) {
        if (__gp == 'get') {
          $.get(__url, __data, function (d) {
            $('#btn' + P_I_BuZou).removeAttr('disabled');
            z_f_200(__url, d);
            z_f_a();
          });
        }
        if (__gp == 'post') {
          $.post(__url, __data, function (d) {
            $('#btn' + P_I_BuZou).removeAttr('disabled');
            z_f_200(__url, d);
            z_f_a();
          });
        }
      } else {
        z_f_a();
      }
    }

    // 禁用进度条按钮。
    function z_f_btn0() {
      $('#btn1').attr('disabled', 'false');
      $('#btn2').attr('disabled', 'false');
      $('#btn3').attr('disabled', 'false');
      $('#btn4').attr('disabled', 'false');
      $('#btn5').attr('disabled', 'false');
      $('#btn6').attr('disabled', 'false');
      $('#btn7').attr('disabled', 'false');
      $('#btn8').attr('disabled', 'false');
      $('#btn9').attr('disabled', 'false');
      P_I_A = 0;
    }

    function z_f_get_akm_url() {
      let old = document.documentElement.outerHTML;
      old = old.replace(
        '<script type="text/javascript" src="/store/_ui/addons/tib2csamplesaddon/responsive/common/js/tib2csamplesaddon.js"></script>',

        '◌'
      );
      old = old.replace(
        '"></script><link rel="stylesheet" type="text/css" href="/_sec/cp_challenge/sec-3-6.css">',
        '◌'
      );

      let aaa = old.split('◌');
      let strAkm = '';
      if (aaa.length >= 2) {
        strAkm = aaa[1].replace(
          '\n\t\t<script type="text/javascript" src="',
          ''
        );
      }
      //z_log("Akm:" + strAkm);
      //console.log(strAkm);
      return strAkm;
    }

    function z_do_403(btn) {
      P_S_Abck_403 = z_GetCookie('_abck');
      z_do_403_1();
      z_do_403_1();
    }

    function z_do_403_1() {
      let ti_sensor_data = '';
      let i_403 = P_I_403 * 1;
      P_I_403 += 1;

      z_log('开始打狗');

      GM_xmlhttpRequest({
        url:
          P_WWW_0_COM +
          '/2.php?_abck=' +
          z_GetCookie('_abck') +
          '&bm_sz=' +
          z_GetCookie('bm_sz'),
        method: 'get',
        data: '',
        headers: {
          'Content-type': 'application/x-www-form-urlencoded',
        },
        onload: function (xhr) {
          if (typeof xhr == 'undefined') {
            z_log('【错误】：GM_xmlhttpRequest');
            return;
          }
          ti_sensor_data = xhr.responseText;
          ti_sensor_data = ti_sensor_data.replace('|>|>|>|>|', '\n');
          let _a = ti_sensor_data.split('\n');
          let _ua = _a[0];
          let _send_data = _a[1];
          console.log(_a);
          //z_log(ti_sensor_data);
          $.ajax({
            type: 'POST',
            url: P_S_AkmUrl,
            data: _send_data,
            Accept: '*/*',
            cache: false,
            async: false,
            beforeSend: function (xhr) {
              xhr.setRequestHeader('User-Agent', _ua);
            },
          }).done(function (d) {
            console.log(d);
            P_I_K_403++;
            z_log('打狗结束。');
          });
        },
        onerror: function (err) {
          z_log('err');
        },
      });
      // 在【GM_xmlhttpRequest】有时候会卡死, 执行 $.ajax.
      // GM_xmlhttpRequest({
      // 	url:
      // 		P_WWW_0_COM +
      // 		'/2.php?_abck=' +
      // 		z_GetCookie('_abck') +
      // 		'&bm_sz=' +
      // 		z_GetCookie('bm_sz'),
      // 	method: 'get',
      // 	data: '',
      // 	headers: {
      // 		'Content-type': 'application/x-www-form-urlencoded',
      // 	},
      // 	onload: function (xhr) {
      // 		if (typeof xhr == 'undefined') {
      // 			z_log('【错误】：GM_xmlhttpRequest');
      // 			return;
      // 		}
      // 		ti_sensor_data = xhr.responseText;

      // 		z_log('--------ti_sensor_data OK----------');

      // 		z_log(ti_sensor_data);

      // 		z_log('-------------------------------');
      // 	},
      // 	onerror: function (err) {
      // 		z_log('err');
      // 	},
      // });

      // setInterval(() => {
      // 	if (ti_sensor_data != '') {
      // 		url = P_S_AkmUrl;
      // 		let data = ti_sensor_data;
      // 		ti_sensor_data = '';
      // 		$.ajax({
      // 			type: 'POST',
      // 			url: url,
      // 			data: data,
      // 			Accept: '*/*',
      // 			cache: false,
      // 			async: false,
      // 		}).done(function (d) {
      // 			//console.log(d);
      // 			P_I_K_403++;
      // 			z_log('结束；');
      // 		});
      // 	}
      // }, 100);
    }
    // 处理返回值 200
    function z_f_200(_url, _data) {
      //debugger;
      //console.log(P_I_A + " | " + _url);

      P_D_JiSi = new Date();
      P_I_A++;
      P_I_FHZ = 200;
      let _zt = 200;
      let _log = '';

      if (typeof _data == 'string') {
        //// console.log(_data
        //   .replace(/<script.*>(\n.*)+<\/script>/, "")
        //   .replace(/<\/?.+?\/?>/g, "")
        //   .replace(/\r\n/g, "")
        // );
        if (_data.indexOf('技术性错误现已中断。') > -1) {
          _log = '技术性错误';
          z_log(P_I_BuZou + ' | Err | ' + _log);
          P_I_BuZou = 999;
          // 抢购结束
        }

        //您购物车中的价格已更改
        if (_data.indexOf('您购物车中的价格已更改') > -1) {
          _log = '您购物车中的价格已更改；请清车后抢购。';
          z_log(P_I_BuZou + ' | Err | ' + _log);
          P_I_BuZou = 999;
          // 抢购结束
        }

        // 提示错误。
        let _err = _data.match(/(?:<(li)>)([^<]+)(?=<\/\1>)/gi);
        if (_err != null) {
          z_log(
            P_I_BuZou + ' | Err | ' + _err[0].split('。')[0].substring(4, 100)
          );
          P_I_BuZou = 999;
        }

        if (_data.indexOf('数量限制：') > -1) {
          z_log(P_I_BuZou + ' | Err | 数量限制');
          P_I_BuZou = 999;
        }

        // 更新配送方式。 //store/ti/zh/checkout/buy/multi/delivery-method/choose
        if (_data.indexOf('id="国际经济快递"') > -1) {
          _data = _data.replace(/\|/g, '');
          _data = _data.replace('<option value="', '|');
          _data = _data.replace('selected="selected"', '|');
          //let _a = _data.replace('|', "").replace('<option value="', '|').replace('selected="selected"', '|').split('|');
          let _a = _data.split('|');
          if (_a.length >= 3) {
            let __a = _a[1].split('"');
            let _s =
              '/buy/multi/delivery-method/select?delivery_method=v2-china-DOM-0_1k-EH&termsAccepted=Yes'.replace(
                'v2-china-DOM-0_1k-EH',
                __a[0]
              );
            $('#txt5url').val(_s);
          }
          // 获取地址。
        }

        // 获取付款地址
        if (_data.indexOf('<iframe') > -1) {
          _data = _data.match(/<iframe\s*src=\"([^\"]*?)\"[^>]*>/gi)[0];
          _log = _data.match(/(http|https){1}:\/\/[^"']*/)[0];
          // 成功抢购
        }
      }
      if (P_I_BuZou != 999) {
        z_log(P_I_BuZou + ' | 200 | ' + _log);
        // 保存数据库
        GM_xmlhttpRequest({
          url:
            P_WWW_0_COM + '/0/p_auto_3.php?opn_sl=' + P_OPN_SL + '&zt=' + _zt,
          method: 'get',
          onload: function (xhr) {
            P_OPN_SL = '';
            //z_log('数据库:更新结束 | ' + _zt);
          },
        });
      }

      P_B_JiSi = false; // 停止计时
    }
    function z_f_403(_url) {
      //debugger;
      //// console.log("z_f_403:" + _url);
      z_f_btn0();
      //z_log("403");
      P_I_FHZ = 403;

      z_f_get_akm_url();
      z_do_403('');
    }
    function z_f_428(_url) {
      //debugger;
      ////console.log("z_f_428:" + _url);
      //z_log("428");
      z_f_btn0();
      P_I_FHZ = 428;
    }
    function z_f_x_200(fhz, _url) {
      //debugger;
      ////console.log("z_f_x_200:" + fhz + " | " + _url);
      //z_log(_url);
      z_f_btn0();
      P_I_FHZ = fhz;
    }

    // 抢购
    function a1() {
      z_f_btn0();
      P_I_BuZou = 0;
      z_f_a();
    }

    // ajax
    function a(m, url, body) {
      let _old_CSRFToken = '11111111-1111-1111-1111-111111111111';
      let _new_CSRFToken = ACC.config.CSRFToken;
      body = body.replace(_old_CSRFToken, _new_CSRFToken);
      if (m == 'post') {
        $.post(url, body, function (d) {
          z_f_200(url, d);
        });
      } else {
        $.get(url, body, function (d) {
          z_f_200(url, d);
        });
      }
    }

    async function f1(_url) {
      //console.log("f1");
      const res = await fetch(_url, {
        credentials: 'include',
        headers: {
          'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0',
          Accept: '*/*',
          'Accept-Language':
            'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
          'Sec-Fetch-Dest': 'script',
          'Sec-Fetch-Mode': 'no-cors',
          'Sec-Fetch-Site': 'same-origin',
        },
        method: 'GET',
        mode: 'cors',
      });
      //console.log(res);
      //console.log("f2");
    }

    // 可以解决跨域
    async function g1(_url) {
      //console.log("g1");
      const res = GM_xmlhttpRequest({
        url: _url,
        method: 'get',
        onload: function (res) {
          //// console.log(xhr.responseText);
          // $('#z_res').html(xhr.responseText);
          //console.log(res);
          //console.log(res.status);
        },
      });
      //console.log(res);
      //console.log("g2");
    }

    // 日志
    function z_log(str) {
      //debugger
      var date = new Date();
      var hour = '00' + date.getHours();
      hour = hour.substr(hour.length - 2);
      var minute = '00' + date.getMinutes();
      minute = minute.substr(minute.length - 2);
      var second = '00' + date.getSeconds();
      second = second.substr(second.length - 2);
      let str_log =
        hour +
        ':' +
        minute +
        ':' +
        second +
        ' | ' +
        z_name +
        ' | ' +
        str +
        '\n';
      console.log(str_log);
      // 记录到数据库？？？
      str_log = str_log + $('#txtLog').val().substring(0, 1000);
      $('#txtLog').val(str_log);
    }
    // -----结束-----

    // websocket 调用
    $('#btnWebSocketLogin').on('click', function () {
      let ip = 'wss://sms.jaxin.net';
      let serverName = 's001';
      initWebSocket(ip, '', serverName);
    });
    // websocket  start
    function initWebSocket(ip, port, serverName) {
      //建立连接
      //初始化weosocket
      // let timestamp = new Date().getTime();
      // const wsuri = "ws://"+ip+":"+port+"/websocket"+"/chip/"+serverName;
      const wsuri = "wss://"+ip+"/websocket"+"/chip/"+serverName;
      try {
        //建立连接
        this.websock = new WebSocket(wsuri);
        //连接成功
        this.websock.onopen = this.websocketonopen;
        //连接错误
        this.websock.onerror = this.websocketonerror;
        //接收信息
        this.websock.onmessage = this.websocketonmessage;
        //连接关闭
        this.websock.onclose = this.websocketclose;
      } catch (e) {
        // this.$message.error('未连接到服务器！');
      }
    }
    function reconnect() {
      //重新连接
      var that = this;
      if (that.lockReconnect) {
        return;
      }
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      that.timeoutNum && clearTimeout(that.timeoutNum);
      that.timeoutNum = setTimeout(function() {
        //新连接
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    }
    function reset() {
      //重置心跳
      var that = this;
      //清除时间
      clearTimeout(that.timeoutObj);
      clearTimeout(that.serverTimeoutObj);
      //重启心跳
      that.start();
    }
    function start() {
      //开启心跳
      let self = this;
      self.timeoutObj && clearTimeout(self.timeoutObj);
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
      self.timeoutObj = setTimeout(function() {
        //这里发送一个心跳，后端收到后，返回一个心跳消息
        if (self.websock.readyState == 1) {
          //如果连接正常
          let msg = {
            code: CLIENT_HEATER_CODE,
            data: 'heat',
            message: ''
          }
          self.websocketsend(JSON.stringify(msg));
          // self.websock.send("100");// 连接请求码100
        } else {
          //否则重连
          self.reconnect();
        }
        self.serverTimeoutObj = setTimeout(function() {
          //超时关闭
          self.websock.close();
        }, self.timeout);
      }, self.timeout);
    }
    function websocketonopen() {
      //连接成功事件
      let msg = {
        code: CLIENT_CONNECTION_CODE,
        data: 'connect',
        message: ''
      }
      this.websocketsend(JSON.stringify(msg));
      //提示成功
      // this.$message.success('连接成功！');
      // console.log("连接成功", 3);
      //开启心跳
      this.start();
    }
    function websocketonerror(e) {
      //连接失败事件
      //错误
      // console.log("WebSocket连接发生错误");
      this.$message.error('未连接到服务器！');
      this.websock = null;
      //重连
      // this.reconnect();
    }
    function websocketclose(e) {
      //连接关闭事件
      //提示关闭
      // console.log("连接已关闭");
      // this.$message.warning('连接已断开！');
      //重连
      // this.reconnect();
    }
    function websocketonmessage(event) {
      let that = this;
      //接收服务器推送的信息
      // console.log("收到服务器信息",event.data);
      let result = JSON.parse(event.data);
      switch(result.code){
        case 2: // 连接请求返回
          let j1 = JSON.parse(result.data);
          that.clientData = [];
          j1.forEach(item => {
            that.clientData.push({
              key: item.id,
              label: item.serverName+'-'+item.groupId+'组',
              disabled: item.connectStatus == 1 ? 0 : 1,
            })
          })
          this.$message.success('连接成功！');
          break;
        case 20: // 连接异常
          this.$message.error(result.message);
          break;
        case 4: // 心跳返回
          // 解析抢购机数据
          let json = JSON.parse(result.data);
          that.clientData = [];
          json.forEach(item => {
            that.clientData.push({
              key: item.id,
              label: item.serverName+'-'+item.groupId+'组',
              disabled: item.connectStatus == 1 ? 0 : 1,
            })
          })
          break;
        case 6:
          // 处理抢购流程
          // alert("处理抢购流程");
          this.$message.success('开始执行抢购流程！');
          $('#z_all').on('click', '#btnAddQg', function () {
            z_f_AddQg();
          });
          break;
        case 8:// 加载数据请求返回
          let arr = JSON.parse(result.data)
          arr.forEach(item => {
            that.goodsList.push({
              code: item
            })
          })
          this.$message.success('数据加载成功！');
          break;
        default:

      }
      //收到服务器信息，心跳重置
      this.reset();
    }
    function websocketsend(msg) {
      //向服务器发送信息
      this.websock.send(msg);
    }
    // websocket end


  }, 100);
})();
